<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button
        type="primary"
        @click="toAdd"
      ><i class="el-icon-plus" />添加权限</el-button>
      <el-table :data="permissionDataList" style="width: 100%">
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column prop="permissionName" label="权限名称" width="180" />
        <el-table-column prop="permissionCode" label="权限编码" width="180" />
        <el-table-column prop="menuName" label="所属菜单" width="180" />
        <el-table-column prop="permissionUrl" label="权限URL" width="280" />
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="warning"
              @click="modifyMenu(scope.row.id)"
            >修改</el-button>
            <el-button
              type="danger"
              @click="removeMenu(scope.row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog
      :title="dialogType === 'Add' ? '新增权限' : '修改权限'"
      :visible.sync="dialogFormVisible"
      width="800px"
    >
      <el-form
        ref="permissionForm"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-row>
          <el-col :span="24">
            <treeselect
              v-model="formData.menuId"
              :options="options"
              :load-options="loadOptions"
              :normalizer="treeSelectProp"
            />
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="权限名称" prop="permissionName">
              <el-input
                v-model="formData.permissionName"
                type="text"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权限编码" prop="permissionCode">
              <el-input
                v-model="formData.permissionCode"
                type="text"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="权限Url" prop="permissionUrl">
              <el-input v-model="formData.permissionUrl" type="text" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="描述" prop="description">
              <el-input
                v-model="formData.description"
                type="textarea"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="savePermission">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  list,
  addPermission,
  deletePermission,
  getPermissionById,
  updatePermission
} from '@/api/permission'
import { deepClone } from '@/utils'
import { getRepeatToken } from '@/api/global'
import { Treeselect, LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { menuTree } from '@/api/menu'
export default {
  name: 'PermissionIndex',
  components: {
    Treeselect
  },
  data() {
    return {
      permissionDataList: [],
      searchEntity: {
        pageNum: 1,
        pageSize: 10,
        entity: {}
      },
      options: [],
      formData: {
        id: '', // 权限ID
        permissionCode: '', // 权限编码
        permissionName: '', // 权限名称
        description: '', // 描述
        updateTime: null, // 修改时间
        menuName: '', // 所属菜单名称
        ext03: '', // 扩展字段3
        createTime: null, // 创建时间
        ext02: '', // 扩展字段2
        ext01: '', // 扩展字段1
        permissionUrl: '', // 权限路径
        createBy: '', // 创建人
        menuId: '', // 菜单ID
        updateBy: '' // 修改人
      },
      rules: {},
      dialogType: 'Add',
      dialogFormVisible: false,
      repeatToken: '',
      temp: []
    }
  },
  created() {
    this.temp = deepClone(this.formData)
    this.initData()
  },
  methods: {
    initData() {
      getRepeatToken().then((res) => {
        this.repeatToken = res.data.token
      })
      list(this.searchEntity).then((res) => {
        this.permissionDataList = res.data.pageInfo.list
      })
    },
    async initMenuTree(id) {
      const res = await menuTree(id)
      this.options = res.data.list
    },
    async initAllMenuTree(id) {
      const menuList = await menuTree(id)
      const list = menuList.data.list
      list.filter(v => {
        menuTree(v.id).then(res => {
          v.children = res.data.list
        })
      })
      this.options = list
    },
    toAdd() {
      this.initMenuTree(-1)
      this.formData = deepClone(this.temp)
      this.dialogType = 'Add'
      this.dialogFormVisible = true
    },
    savePermission() {
      this.$refs['permissionForm'].validate((valid) => {
        if (valid) {
          if (this.dialogType == 'Add') {
            addPermission(this.formData, { token: this.repeatToken })
              .then((res) => {
                if (res.meta.code == 200) {
                  this.$message.success('操作成功!')
                  this.dialogFormVisible = false
                }
                this.initData()
              })
              .catch((err) => {
                this.initData()
              })
          } else {
            updatePermission(this.formData, { token: this.repeatToken })
              .then((res) => {
                if (res.meta.code == 200) {
                  this.$message.success('操作成功!')
                  this.dialogFormVisible = false
                }
                this.initData()
              })
              .catch((err) => {
                this.initData()
              })
          }
        } else {
          return false
        }
      })
    },
    loadOptions({ action, parentNode, callback }) {
      if (action === LOAD_CHILDREN_OPTIONS) {
        menuTree(parentNode.id).then((res) => {
          console.log(res.data.list)
          parentNode.children = res.data.list
          callback()
        })
      }
    },
    treeSelectProp(node) {
      if (node.id == '') {
        return {
          id: node.id,
          label: '请选择所属菜单',
          children: []
        }
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },
    removeMenu(id) {
      this.$confirm('此操作将永久删除该权限,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deletePermission(id, { token: this.repeatToken }).then((res) => {
            if (res.meta.code == 200) {
              this.$message.success('删除成功!')
              this.initData()
            }
          })
        })
        .catch(() => {})
    },
    modifyMenu(id) {
      this.initAllMenuTree(-1)
      this.dialogType = 'Mod'
      getPermissionById(id).then((res) => {
        this.formData = res.data.data
        this.dialogFormVisible = true
      })
    }
  }
}
</script>
